package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
	"go_shengshu_admin/config"
	"go_shengshu_admin/handler"
	"go_shengshu_admin/model"
	"go_shengshu_admin/repository"
	"go_shengshu_admin/service"
	"log"
)

var (
	DB              *gorm.DB
	BannerHandler   handler.BannerHandler
	CategoryHandler handler.CategoryHandler
	OrderHandler    handler.OrderHandler
	ProductHandler  handler.ProductHandler
	UserHandler     handler.UserHandler
)

func Init() {
	initViper()
	initDB()
	initHandler()

}

func initViper() {
	if err := config.Init("config"); err != nil {
		panic(err)
	}
}

func initDB() {
	fmt.Sprint("db init...")
	var err error
	conf := &model.DBConf{
		Host:     viper.GetString("database.host"),
		User:     viper.GetString("database.username"),
		Password: viper.GetString("database.password"),
		DbName:   viper.GetString("database.name"),
	}
	config := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=%t&loc=%s",
		conf.User,
		conf.Password,
		conf.Host,
		conf.DbName, true, "Local")
	DB, err = gorm.Open("mysql", config)
	if err != nil {
		log.Fatalf("db connect error ... %s", err)
	}
	DB.SingularTable(true) //表名不带s
	DB.AutoMigrate(&model.Product{})
	DB.AutoMigrate(&model.Order{})
	DB.AutoMigrate(&model.User{})
	DB.AutoMigrate(&model.Banner{})
	DB.AutoMigrate(&model.Category{})
	fmt.Sprint("db init complete ...")

}

func initHandler() {
	BannerHandler = handler.BannerHandler{
		Srv: &service.BannerService{
			Repo: &repository.BannerRepository{
				DB: DB,
			},
		}}

	CategoryHandler = handler.CategoryHandler{
		Srv: &service.CategoryService{
			Repo: &repository.CategoryRepository{
				DB: DB,
			},
		}}
	OrderHandler = handler.OrderHandler{
		Srv: &service.OrderService{
			Repo: &repository.OrderRepository{
				DB: DB,
			},
		}}
	ProductHandler = handler.ProductHandler{
		Srv: &service.ProductService{
			Repo: &repository.ProductRepository{
				DB: DB,
			},
		}}

	UserHandler = handler.UserHandler{
		Srv: &service.UserService{
			Repo: &repository.UserRepository{
				DB: DB,
			},
		}}
}
